<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

class Login extends Controller {

	function setVars()
	{
		$this->tpl['title'] = 'Login';
        $this->tpl['sidebar'] = $this->tm->randomBlock();
		$this->tpl['head'] = '';
	}
	
	function __construct()
	{
		parent::Controller();
        $this->load->model('Tamer_Model', 'tm');
		$this->setVars();
        // $this->load->library('profiler');
		log_message('debug', "Login Controler Class Initialized");
	}

/*****************************************************************\
|               LOGIN
\*****************************************************************/	
	function Index()
	{
        $this->load->helper('form');
        
        define('URI',$this->uri->segment(1).'/'.$this->uri->segment(2));
		if(isset($_POST['Alias']))
		{
			$this->postCheck();
		}
        $Alias = $this->session->userdata('Alias');
        if($Alias !== FALSE){
            $checked = TRUE;
            $infoBlock1 = '<h3>Please verify your password</h3>';
            $this->tpl['sidebar'] = '<h2 class="SideBar">Why am I being asked for my password?</h2>For your security, we will always prompt you for your password when accessing sensitive areas, like Account Info.';
            $infoBlock2 = '<hr />Not '.$Alias.'? '.anchor('control_panel/login/logout','Logout').' to sign in as a different user.';
            $form[1]['Alias']  = $Alias;
            $form[''][] = form_hidden('Alias', $Alias);

        }else{
        	$Alias = '';
            $checked = FALSE;
            $infoBlock1 = '';
            $infoBlock2 = '';
            
            $class='';
            if(isset($this->validation->Alias_error) || isset($this->validation->login_check_error)){
                $class='FormErr'; 
            }
            $form[1]['Alias'] = form_input(array(
                'name'        => 'Alias',
                'id'          => 'Alias',
                'value'       =>  $Alias,
                'size'        => '10',
                'maxlength'   => '20',
                'class'       => $class,
                'autocomplete' => 'off'
                )
            );
        }
        
        $class='';
        if(isset($this->validation->Password_error) || isset($this->validation->login_check_error)){
            $class='FormErr'; 
        }
        $form[1]['Password'] = form_password(array(
            'name'        => 'Password',
            'id'          => 'Password',
            'value'       => '',
            'size'        => '10',
            'maxlength'   => '20',
            'class'       => $class,
            'style'       => '',
            'autocomplete' => 'off'
            )
        );

        if($Alias == ''){
        $form['  '] =  form_checkbox(array(
                                    'name'        => 'save',
                                    'id'          => 'save',
                                    'value'       => '1',
                                    'checked'     => $checked,
                                    'style'       => 'margin:10px;'
                                    )
                                ).'Remember me on this computer';
        }
        
        $form[''][] =          form_submit(array('class' => 'submit', 
                                    'name'        => 'login',
                                    'value'       => 'Login',
                                    'style'       => 'margin:10px'
                                    )
                                ).anchor('control_panel/register', 'Register',array('title'=>'Click here to register'));
        $this->load->library('table');
        $attributes = '';
        $this->tpl['body'] = form_open(URI, $attributes);
        $this->tpl['body'] .= $infoBlock1;
        $this->tpl['body'] .= $this->table->form_table($form);
        $this->tpl['body'] .= '</form>';
        $this->tpl['body'] .= $infoBlock2;

        $this->load->view('blank', $this->tpl);
	}



	function postCheck()
	{
		$this->load->library('validation');
		$rules['Alias']	= "trim|required|alpha_numeric|xss_clean";
		$rules['Password']	= "trim|required|alpha_numeric|xss_clean";
		$this->validation->set_rules($rules);
		$fields['Alias'] = 'Alias';
		$fields['Password'] = 'Password';
		$this->validation->set_fields($fields);
		if ($this->validation->run() === TRUE)
		{
			$rules['login'] = "callback_login_check"; # Calling login check
			$this->validation->set_rules($rules) ;
            $this->validation->run();
		}
	}

	/***************************************************\
	*	If post is correct we will login
	\***************************************************/
	function login_check()
	{
		$alias = $this->validation->Alias;
		$pass  = $this->validation->Password;
		$save  = $this->input->post('save');
		$query = $this->db->getwhere('contact_user', array('Alias' => $alias, 'Password' => $pass), 1);
        if($query->num_rows() > 0) {
            $data = $query->row();
            $data->groups .= ',100';
            $data->login = TRUE;
            $this->session->set_userdata($data);
            del_cookie('TZ');
            set_cookie('Alias', $alias, 60*60*24*365);
            if($this->session->userdata('login_check') > 0){
                $c = $this->session->ro_userdata('login_check');
            }
            if($save == 1) $this->auth->addCookie();
            
            $where = array('uid' => $data->uid, 'State' => 'Pending');
            $query = $this->db->getwhere('Ticket', $where);
            if ($query->num_rows() > 0)
            {
                redirect('ticket', 'location');
            }else{
                redirect('control_panel/index', 'location');
            }
        }
		else
		{
            $c=1;
            $i = (int) $this->session->userdata('login_check');
            if($c>0){
                $c=$i+1;
            }
            $this->session->set_userdata('login_check', $c);
			$this->validation->set_message('login_check', 'We have no match.<br />Counting '. $c);
			return FALSE;
		}
	}

	/*****************************************************************\
	|               LOGOUT
	\*****************************************************************/

	function LogOut()
	{
		$this->auth->Logout();
	}
}
?>
